import { Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { ISelectionUserBackData } from '@app/shared/common/workflow/workflow-common-interface';
import { SelectionUserBoxModalComponent } from '@app/shared/common/workflow/wrokflow-common-component/selection-user-box.component';
import { AppModalComponentBase } from '@shared/common/app-modal-component-base';
import { CreateFlowNodeInput, FlowNodeDto, GetFLowNodeForEditOutput, NameValue, NameValueOfInt32, PagedFlowNodeDto, PostItemData, UpdateFlowNodeInput, WorkFlowDesignServiceProxy } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'flow-node-detail-modal',
  templateUrl: './flow-node-detail-modal.component.html'
})
export class FlowNodeDetailModalComponent extends AppModalComponentBase {

    @ViewChild('editModal', { static: true }) modal: ModalDirective;
    @Output() flowNodeDetailModalSave: EventEmitter<any> = new EventEmitter<any>();
    @ViewChild('selectUserModal',{static: true}) selectUserModal:SelectionUserBoxModalComponent;

    saving = false;
    workFlowId:string;
    flowNodeId:string;

    allNodes:PagedFlowNodeDto[] = [];
    actionNames:NameValue[] = [];
    posts:PostItemData[] = [];
    operatorFilterSource:NameValueOfInt32[] = [];
    functions:NameValue[] = [];
    actionSchemeList:NameValue[] = [];
    selectNextNodes:PagedFlowNodeDto[] = [];
    selectBackNodes:PagedFlowNodeDto[] = [];
    selectedActionNames:NameValue[] = [];
    beforeSelectFilter2:PostItemData[] = [];
    selectedFilter2:PostItemData[] = [];
    isHasPapers:boolean = false;
    fields:FlowNodeDto = new FlowNodeDto()
    constructor(
        injector: Injector,
        private _workFlowDesignServiceProxy:WorkFlowDesignServiceProxy
    ) {
        super(injector);
    }

    
    show(workFlowId:string,nodeId:string): void {
        this.modalExpandOb.resetStates();
        if (!workFlowId) {
           return;
        }
        this.resetData();
        this.workFlowId = workFlowId;
        this.flowNodeId = nodeId;
        this.modal.show();
        this.initData();
    }


    save(): void {
        
        let selectNextNodeIds = this.selectNextNodes.map(item=>item.id);
        let selectBackNodeIds = this.selectBackNodes.map(item=>item.id);
        let actionNames = this.selectedActionNames.map(item=>item.value);
        let selectedFilterIds = this.selectedFilter2.map(item=>item.unqiueName);
        let beforeSelectFilterIds = this.beforeSelectFilter2.map(item=>item.unqiueName);

        this.fields.nextNodeList = selectNextNodeIds.join(',');
        this.fields.backNodeList = selectBackNodeIds.join(',');
        this.fields.actionList = actionNames.join(',');
        this.fields.selectedMoreFilter = selectedFilterIds.join(',');
        this.fields.beforeSelectMoreFilter = beforeSelectFilterIds.join(',');

        if (this.fields.id && this.fields.id !=="00000000-0000-0000-0000-000000000000") {
            this.saving = true;
            let updateFlowNodeInput = new UpdateFlowNodeInput();
            Object.assign(updateFlowNodeInput,this.fields);
            this._workFlowDesignServiceProxy.updateFlowNode(updateFlowNodeInput).pipe(finalize(() => { this.saving = false; })).subscribe(res=>{
                this.notify.success(this.l('SavedSuccessfully'))
                this.flowNodeDetailModalSave.emit(true);
                this.close();
                this.saving = false;
            })
            
        }
        else {
            this.saving = true;
            let createFlowNodeInput = new CreateFlowNodeInput();
            Object.assign(createFlowNodeInput,this.fields);
            this._workFlowDesignServiceProxy.createFlowNode(createFlowNodeInput).pipe(finalize(() => { this.saving = false; })).subscribe(res=>{
                this.notify.success(this.l('SavedSuccessfully'))
                this.flowNodeDetailModalSave.emit(true);
                this.close();
                this.saving = false;
            });
        }
    }

    close(): void {
        this.modal.hide();
    }

    selectionUsers(){
        this.selectUserModal.show(this.fields.userIdList,this.workFlowId);
    }

    dbSelectItem(item, selectedCollection){
        if (selectedCollection.indexOf(item) < 0) {
            selectedCollection.push(item);
        }
    }

    clear(selectedCollection){
        selectedCollection.length = 0;
    }

    dbRemoveItem(item, selectedCollection){
        var i = selectedCollection.indexOf(item);
        if (i > -1) {
            selectedCollection.splice(i, 1);
        }
    }

    selectionUserBackData(data:ISelectionUserBackData){
        this.fields.userIdList = data.ids;
        this.fields.userNames = data.names;
    }

    private initData(){
        this._workFlowDesignServiceProxy.getFlowNode(this.workFlowId,this.flowNodeId).subscribe(res=>{
            this.operatorFilterSource = res.operatorFilterSource;
            this.posts = res.posts;
            this.functions = res.functions;
            this.actionNames = res.actionNames;
            this.actionSchemeList = res.actionSchemeList;
            this.isHasPapers = res.isHasPapers;
            this.fields = res.flowNode;
            this.selectedActionNames = this.getSelectedItemsByIdList(this.fields.actionList,this.actionNames,'value');
            this.beforeSelectFilter2 = this.getSelectedItemsByIdList(this.fields.beforeSelectMoreFilter,this.posts,'unqiueName');
            this.selectedFilter2 = this.getSelectedItemsByIdList(this.fields.selectedMoreFilter,this.posts,'unqiueName');

            this.getAllFlowNodes();
        });
    }

    private resetData(){
        this.operatorFilterSource = [];
        this.posts = [];
        this.functions = [];
        this.actionNames = [];
        this.actionSchemeList = [];
        this.isHasPapers = false;
        this.fields = new FlowNodeDto();
        this.selectedActionNames = [];
        this.beforeSelectFilter2 = [];
        this.selectedFilter2 = [];
        this.allNodes = [];
        this.selectNextNodes = [];
        this.selectBackNodes = [];
    }


    private getAllFlowNodes(){
        this._workFlowDesignServiceProxy.getPagedFlowNode(this.workFlowId).subscribe(res=>{
            let jsonData = res;
            this.allNodes = jsonData;
            let index = -1;
            for (let i = 0; i < jsonData.length; i++) {
                const item = jsonData[i];
                if (item.id == this.flowNodeId){
                    index = i;
                }
            }

            if (index > -1){
                this.allNodes.splice(index,1);
            }

            this.selectNextNodes = this.getSelectedItemsByIdList(this.fields.nextNodeList, this.allNodes, 'id');
            this.selectBackNodes = this.getSelectedItemsByIdList(this.fields.backNodeList, this.allNodes, 'id');
         
        });
    }

    private  getSelectedItemsByIdList(idList:string, data, key:string) {
        var arr = [], i:number, j:number, tempId:string, item:PagedFlowNodeDto;
        if (idList) {
            var splitIds = idList.split(',');
            for (i = 0; i < splitIds.length; i++) {
                tempId = splitIds[i];
                for (j = 0; j < data.length; j++) {
                    item = data[j];
                    if (tempId === item[key]) {
                        arr.push(item);
                    }
                }
            }
        }
        return arr;
    }
 
}
